<template>
<div>
  <div class="crumbs">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/analysis' }">
        <i class="el-icon-pie-chart"></i> 数据统计分析列表
      </el-breadcrumb-item>
      <el-breadcrumb-item>
        <i class="el-icon-lx-cascades"></i> 分析结果
      </el-breadcrumb-item>
    </el-breadcrumb>
  </div>

  <div class="container">
    <el-table
        :data="tableData" border class="table" ref="multipleTable"
        header-cell-class-name="table-header"
    >
      <el-table-column prop="analysisConfigId" label="配置id"></el-table-column>
      <el-table-column label="分析方法">
        <template #default="scope">{{ scope.row.analysisFunction }}</template>
      </el-table-column>
      <el-table-column label="结果">
        <template #default="scope">
          <div v-if="scope.row.analysisFunction === 'SCATTER_PLOT'">
              请移步可视化👉
          </div>
          <div v-else>
            {{ scope.row.analysisResult }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" align="center">
        <template #default="scope">
            <el-button type="text" icon="el-icon-view"
                       @click="handleVisualize(scope.$index)">可视化
            </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <el-dialog v-model="visualizeVisible" title="可视化" @open="open(chart.analysisFunction)" width="700px">
    <el-form :model="chart" width="400px">
      <el-form-item label="分析函数: " >
          {{chart.analysisFunction}}
      </el-form-item>
      <el-form-item label="分析结果: " v-if="chart.analysisFunction!=='SCATTER_PLOT'">
        {{chart.analysisResult}}
      </el-form-item>
      <el-form-item label="可视化: " v-if="chart.analysisFunction === 'DATA_DISTRIBUTION'">
        <div id="chartPie" style="width: 600px;height: 300px" ></div>
      </el-form-item>
      <el-form-item label="可视化: " v-if="chart.analysisFunction === 'SCATTER_PLOT'">
        <div id="scatter" style="width: 600px;height: 300px" ></div>
      </el-form-item>

  </el-form>
  </el-dialog>
</div>
</template>

<script>
import {useRoute} from "vue-router";
import {inject, nextTick, reactive, ref} from "vue";
import {getAnalysisByConfig} from "../../api/analysis";

export default {
  name: "AnalysisHistory",
  setup(){
    const tableData = ref([]);
    const configId = ref();
    let visualizeVisible = ref(false)
    const chart = reactive({
      analysisFunction: '',
      analysisResult: {},
      pieResult: {},
    })
    let scatterData = ref([])
    let scatterKey = ref([])

    const echarts = inject('echarts')
    const echartsScatter = inject('echarts')

    const getData = () => {
      const route=useRoute()
      const payload={
        userId: localStorage.getItem("ms_userId"),
        configId: route.query.configId
      }
      if(route.query.configId!=null) {
        getAnalysisByConfig(payload).then(res => {
          tableData.value = res.result;
          for (let i=0;i<tableData.value.length;i++){
            //tableData.value[i].analysisResult=tableData.value[i].analysisResult
            console.log(tableData.value[i].analysisResult)
          }
          configId.value=route.query.configId
        })
      }
    };
    getData();

    const handleVisualize = (index) => {
      chart.analysisFunction = tableData.value[index].analysisFunction

      if(chart.analysisFunction === 'SCATTER_PLOT'){
        let tempArr= JSON.parse(tableData.value[index].analysisResult)
        let tempObj = tempArr[0]
        let out_arr = []
        for(let key in tempObj){
          out_arr.push(key)
        }
        scatterKey = out_arr
        let tempScatterData = []
        for (let i in tempArr){
          let temp = []
          for (let j in tempArr[i]){
            temp.push(tempArr[i][j])
          }
          tempScatterData.push(temp)
        }
        scatterData = tempScatterData
      }
      else {
        chart.analysisResult = tableData.value[index].analysisResult
      }

      visualizeVisible.value = true

      if(chart.analysisFunction === 'DATA_DISTRIBUTION'){
        let out_arr = []
        let in_obj = JSON.parse(chart.analysisResult)
        for(let key in in_obj){
          let temp = {};			//创建临时对象
          temp.name = key;		//存储对象的Key为name
          temp.value = in_obj[key];	//存储value
          out_arr.push(temp);
        }
        chart.pieResult = out_arr
      }

    }

    const drawChart = () => {
      let myChart = echarts.init(document.getElementById("chartPie"));
      myChart.setOption({
        //鼠标悬浮
        tooltip: {
          trigger: "item",
          // formatter: "{a}<br/>{b}: <br/>{c}({d}%)",  其中 {a}指向name名称（访问来源）
          formatter: "{b}: <br/>{c}({d}%)",
        },
        // legend: {
        //   // data: ["直接访问", "邮件营销", "联盟广告", "视频广告", "搜索引擎"],
        //   right: 300,
        //   orient: "vertical",
        //   // 下面注释的代码是控制分类放在哪个地方,需要体验的话，直接把上面的代码注释，把下面的代码解开注释即可
        //     data: ["红", "黄", "绿"],
        //     // left: "center",
        //     // top: "bottom",
        //     // orient: "horizontal"
        // },
        series: [
          {
            name: "???",
            type: "pie",
            //圆圈的粗细
            radius: ["50%", "80%"],
            //圆圈的位置
            center: ["50%", "50%"],
            data:  chart.pieResult,
            animationDuration: 2000,
            //控制是否显示指向文字的,默认为true
            label: {
              // show: false,
              // position: "center",
              //以下代码可以代表指向小文字的
                show: true,
                formatter: "{b} : {d}%",
                textStyle: {
                  color: "#333",
                  fontSize: 14,
                },
            },
          },
        ],
      })
      window.onresize = function () {
        myChart.resize()
      }
    }

    const drawScatter = () => {
      let myChart = echartsScatter.init(document.getElementById("scatter"));
      myChart.setOption({
        color: [
          '#dd4444', '#fec42c', '#80F1BE'
        ],
        grid:{
          right: '20%'
        },
        tooltip: {
          //十字线
          axisPointer: {
            type: 'cross'
          },
          padding: 10,
          backgroundColor: '#222',
          borderColor: '#777',
          borderWidth: 1,
          //设置tooltip的显示内容
          formatter: function (obj) {
            let value = obj.value;
            return '<div style="border-bottom: 1px solid rgba(255,255,255,.3); font-size: 18px;padding-bottom: 7px;margin-bottom: 7px">'
                +  '具体数据：'
                + '</div>'
                + scatterKey[0] + '：' + value[0] + '<br>'
                + scatterKey[1] + '：' + value[1] + '<br>'
                + scatterKey[2] + '：' + value[2] + '<br>'
          }
        },
        xAxis: {
          name: scatterKey[0],
          splitLine: {
            show: false
          },
        },
        yAxis: {
          name: scatterKey[1],
          splitLine: {
            show: false
          }
        },
        visualMap: [
          {
            left: 'right',
            top: '10%',
            dimension: 2,
            min: 0,
            max: 20,
            itemWidth: 30,
            itemHeight: 120,
            calculable: false,
            precision: 0.1,
            text: ['个数'],
            textGap: 30,
            inRange: {
              symbolSize: [10, 70]
            },
            outOfRange: {
              symbolSize: [10, 70],
              color: ['rgba(255,255,255,.2)']
            },
            controller: {
              inRange: {
                color: ['#c23531']
              },
              outOfRange: {
                color: ['#444']
              }
            }
          },
        ],

        series: [
          {
            type: 'scatter',
            itemStyle: {
              shadowBlur: 10,
              shadowColor: 'rgba(120, 36, 50, 0.5)',
              shadowOffsetY: 5,
            },
            data: scatterData,
          }
        ]
      })
      window.onresize = function () {
        myChart.resize()
      }
    }


    const open = (func) =>{
      if (func === 'DATA_DISTRIBUTION'){
        nextTick(() => {
          drawChart()
        })
      }
      else if (func === 'SCATTER_PLOT'){
        nextTick(() => {
          drawScatter()
        })
      }
    }

    return{
      tableData,
      visualizeVisible,
      chart,
      echarts,
      echartsScatter,
      scatterData,
      scatterKey,
      getData,
      handleVisualize,
      drawChart,
      drawScatter,
      open,
    };
  }
}
</script>

<style scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}
.table {
  width: 100%;
  font-size: 14px;
}
.red {
  color: #ff0000;
}
.green {
  color: rgb(32, 220, 88)
}
.yellow{
  color:yellowgreen;
}
.mr10 {
  margin-right: 10px;
}
.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
</style>
